<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>书籍请求列表 - ZLibLike平台</title>
    <link rel="stylesheet" href="/css/bootstrap.min.css">
    <link rel="stylesheet" href="/css/style.css">
</head>
<body>
    <div th:replace="~{commons/header :: header}"></div>
    
    <div class="container mt-4">
        <div class="row mb-4">
            <div class="col-md-6">
                <h2>书籍请求列表</h2>
            </div>
            <div class="col-md-6 text-right">
                <a href="/book-request-form.html" class="btn btn-primary">
                    <i class="fa fa-plus"></i> 提交新请求
                </a>
            </div>
        </div>
        
        <div class="card">
            <div class="card-header bg-light">
                <ul class="nav nav-tabs card-header-tabs" id="requestTabs">
                    <li class="nav-item">
                        <a class="nav-link active" id="all-tab" data-toggle="tab" href="#all">所有请求</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" id="my-tab" data-toggle="tab" href="#my">我的请求</a>
                    </li>
                </ul>
            </div>
            <div class="card-body">
                <div class="tab-content" id="requestTabContent">
                    <!-- 所有请求 Tab -->
                    <div class="tab-pane fade show active" id="all" role="tabpanel">
                        <div class="form-row mb-3">
                            <div class="col-md-3">
                                <select id="allStatusFilter" class="form-control">
                                    <option value="">所有状态</option>
                                    <option value="待处理">待处理</option>
                                    <option value="已接受">已接受</option>
                                    <option value="已拒绝">已拒绝</option>
                                    <option value="已完成">已完成</option>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <button id="allSearchBtn" class="btn btn-secondary">
                                    <i class="fa fa-search"></i> 筛选
                                </button>
                            </div>
                        </div>
                        
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>标题</th>
                                        <th>作者</th>
                                        <th>请求者</th>
                                        <th>状态</th>
                                        <th>创建时间</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody id="allRequestsTable">
                                    <!-- 数据将通过JavaScript动态加载 -->
                                </tbody>
                            </table>
                        </div>
                        
                        <div id="allPagination" class="d-flex justify-content-center">
                            <!-- 分页将通过JavaScript动态加载 -->
                        </div>
                        
                        <div id="allEmpty" class="text-center p-4 d-none">
                            <p>暂无书籍请求</p>
                        </div>
                    </div>
                    
                    <!-- 我的请求 Tab -->
                    <div class="tab-pane fade" id="my" role="tabpanel">
                        <div class="form-row mb-3">
                            <div class="col-md-3">
                                <select id="myStatusFilter" class="form-control">
                                    <option value="">所有状态</option>
                                    <option value="待处理">待处理</option>
                                    <option value="已接受">已接受</option>
                                    <option value="已拒绝">已拒绝</option>
                                    <option value="已完成">已完成</option>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <button id="mySearchBtn" class="btn btn-secondary">
                                    <i class="fa fa-search"></i> 筛选
                                </button>
                            </div>
                        </div>
                        
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>标题</th>
                                        <th>作者</th>
                                        <th>状态</th>
                                        <th>创建时间</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody id="myRequestsTable">
                                    <!-- 数据将通过JavaScript动态加载 -->
                                </tbody>
                            </table>
                        </div>
                        
                        <div id="myPagination" class="d-flex justify-content-center">
                            <!-- 分页将通过JavaScript动态加载 -->
                        </div>
                        
                        <div id="myEmpty" class="text-center p-4 d-none">
                            <p>您还没有提交过书籍请求</p>
                            <a href="/book-request-form.html" class="btn btn-primary mt-2">
                                <i class="fa fa-plus"></i> 提交新请求
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 处理请求模态框 -->
    <div class="modal fade" id="processModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">处理请求</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="processForm">
                        <input type="hidden" id="processRequestId">
                        
                        <div class="form-group">
                            <label>请求状态</label>
                            <select id="processStatus" class="form-control">
                                <option value="已接受">接受请求</option>
                                <option value="已拒绝">拒绝请求</option>
                                <option value="已完成">标记为已完成</option>
                            </select>
                        </div>
                        
                        <div id="rejectReasonGroup" class="form-group d-none">
                            <label for="rejectReason">拒绝原因</label>
                            <textarea id="rejectReason" class="form-control" rows="3"></textarea>
                        </div>
                        
                        <div id="bookIdGroup" class="form-group d-none">
                            <label for="bookId">关联书籍ID</label>
                            <input type="number" id="bookId" class="form-control" min="1">
                            <small class="form-text text-muted">请输入已上传的书籍ID</small>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="submitProcess">提交</button>
                </div>
            </div>
        </div>
    </div>
    
    <div th:replace="~{commons/footer :: footer}"></div>
    
    <script src="/js/jquery-3.6.0.min.js"></script>
    <script src="/js/bootstrap.bundle.min.js"></script>
    <script th:inline="javascript">
        $(document).ready(function() {
            // 初始页面设置
            let allCurrentPage = 1;
            let myCurrentPage = 1;
            const pageSize = 10;
            let allStatus = '';
            let myStatus = '';
            
            // 加载初始数据
            loadAllRequests(1);
            
            // 标签页切换事件
            $('#requestTabs a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
                if (e.target.id === 'my-tab') {
                    loadMyRequests(1);
                }
            });
            
            // 所有请求筛选按钮点击事件
            $('#allSearchBtn').click(function() {
                allStatus = $('#allStatusFilter').val();
                loadAllRequests(1);
            });
            
            // 我的请求筛选按钮点击事件
            $('#mySearchBtn').click(function() {
                myStatus = $('#myStatusFilter').val();
                loadMyRequests(1);
            });
            
            // 加载所有请求
            function loadAllRequests(page) {
                allCurrentPage = page;
                let url = `/api/book-requests?page=${page}&size=${pageSize}`;
                if (allStatus) {
                    url += `&status=${allStatus}`;
                }
                
                fetch(url)
                    .then(response => response.json())
                    .then(data => {
                        if (data.status === 200) {
                            const result = data.data;
                            
                            if (result.records.length === 0) {
                                $('#allEmpty').removeClass('d-none');
                                $('#allRequestsTable').html('');
                                $('#allPagination').html('');
                            } else {
                                $('#allEmpty').addClass('d-none');
                                renderAllRequestsTable(result.records);
                                renderPagination('all', result.currentPage, result.totalPages);
                            }
                        } else {
                            alert(data.message);
                        }
                    })
                    .catch(error => console.error('Error:', error));
            }
            
            // 加载我的请求
            function loadMyRequests(page) {
                myCurrentPage = page;
                let url = `/api/book-requests/my?page=${page}&size=${pageSize}`;
                if (myStatus) {
                    url += `&status=${myStatus}`;
                }
                
                fetch(url)
                    .then(response => response.json())
                    .then(data => {
                        if (data.status === 200) {
                            const result = data.data;
                            
                            if (result.records.length === 0) {
                                $('#myEmpty').removeClass('d-none');
                                $('#myRequestsTable').html('');
                                $('#myPagination').html('');
                            } else {
                                $('#myEmpty').addClass('d-none');
                                renderMyRequestsTable(result.records);
                                renderPagination('my', result.currentPage, result.totalPages);
                            }
                        } else {
                            alert(data.message);
                        }
                    })
                    .catch(error => console.error('Error:', error));
            }
            
            // 渲染所有请求表格
            function renderAllRequestsTable(records) {
                let html = '';
                
                records.forEach(record => {
                    const createdAt = new Date(record.createdAt).toLocaleString();
                    
                    html += `
                        <tr>
                            <td>${record.title}</td>
                            <td>${record.author}</td>
                            <td>${record.requesterName}</td>
                            <td><span class="badge ${getStatusBadgeClass(record.status)}">${record.status}</span></td>
                            <td>${createdAt}</td>
                            <td>
                                <a href="/book-request-detail.html?id=${record.requestId}" class="btn btn-sm btn-info">
                                    <i class="fa fa-eye"></i> 查看
                                </a>
                                <button class="btn btn-sm btn-primary process-btn" data-id="${record.requestId}">
                                    <i class="fa fa-cog"></i> 处理
                                </button>
                            </td>
                        </tr>
                    `;
                });
                
                $('#allRequestsTable').html(html);
                
                // 处理按钮点击事件
                $('.process-btn').click(function() {
                    const requestId = $(this).data('id');
                    openProcessModal(requestId);
                });
            }
            
            // 渲染我的请求表格
            function renderMyRequestsTable(records) {
                let html = '';
                
                records.forEach(record => {
                    const createdAt = new Date(record.createdAt).toLocaleString();
                    
                    html += `
                        <tr>
                            <td>${record.title}</td>
                            <td>${record.author}</td>
                            <td><span class="badge ${getStatusBadgeClass(record.status)}">${record.status}</span></td>
                            <td>${createdAt}</td>
                            <td>
                                <a href="/book-request-detail.html?id=${record.requestId}" class="btn btn-sm btn-info">
                                    <i class="fa fa-eye"></i> 查看
                                </a>
                                ${record.status === '待处理' ? `
                                <button class="btn btn-sm btn-danger delete-btn" data-id="${record.requestId}">
                                    <i class="fa fa-trash"></i> 删除
                                </button>
                                ` : ''}
                            </td>
                        </tr>
                    `;
                });
                
                $('#myRequestsTable').html(html);
                
                // 删除按钮点击事件
                $('.delete-btn').click(function() {
                    const requestId = $(this).data('id');
                    deleteRequest(requestId);
                });
            }
            
            // 渲染分页
            function renderPagination(type, currentPage, totalPages) {
                if (totalPages <= 1) {
                    $(`#${type}Pagination`).html('');
                    return;
                }
                
                let html = '<nav><ul class="pagination">';
                
                // 上一页
                if (currentPage > 1) {
                    html += `<li class="page-item"><a class="page-link" href="#" data-page="${currentPage - 1}">上一页</a></li>`;
                } else {
                    html += `<li class="page-item disabled"><a class="page-link" href="#">上一页</a></li>`;
                }
                
                // 页码
                const startPage = Math.max(1, currentPage - 2);
                const endPage = Math.min(totalPages, startPage + 4);
                
                for (let i = startPage; i <= endPage; i++) {
                    if (i === currentPage) {
                        html += `<li class="page-item active"><a class="page-link" href="#">${i}</a></li>`;
                    } else {
                        html += `<li class="page-item"><a class="page-link" href="#" data-page="${i}">${i}</a></li>`;
                    }
                }
                
                // 下一页
                if (currentPage < totalPages) {
                    html += `<li class="page-item"><a class="page-link" href="#" data-page="${currentPage + 1}">下一页</a></li>`;
                } else {
                    html += `<li class="page-item disabled"><a class="page-link" href="#">下一页</a></li>`;
                }
                
                html += '</ul></nav>';
                
                $(`#${type}Pagination`).html(html);
                
                // 分页点击事件
                $(`#${type}Pagination .page-link`).click(function(e) {
                    e.preventDefault();
                    const page = $(this).data('page');
                    if (page) {
                        if (type === 'all') {
                            loadAllRequests(page);
                        } else {
                            loadMyRequests(page);
                        }
                    }
                });
            }
            
            // 打开处理请求模态框
            function openProcessModal(requestId) {
                $('#processRequestId').val(requestId);
                $('#processStatus').val('已接受');
                $('#rejectReasonGroup').addClass('d-none');
                $('#bookIdGroup').addClass('d-none');
                $('#processModal').modal('show');
            }
            
            // 状态选择变更事件
            $('#processStatus').change(function() {
                const status = $(this).val();
                
                if (status === '已拒绝') {
                    $('#rejectReasonGroup').removeClass('d-none');
                    $('#bookIdGroup').addClass('d-none');
                } else if (status === '已完成') {
                    $('#rejectReasonGroup').addClass('d-none');
                    $('#bookIdGroup').removeClass('d-none');
                } else {
                    $('#rejectReasonGroup').addClass('d-none');
                    $('#bookIdGroup').addClass('d-none');
                }
            });
            
            // 提交处理请求
            $('#submitProcess').click(function() {
                const requestId = $('#processRequestId').val();
                const status = $('#processStatus').val();
                
                const updateDTO = {
                    requestId: parseInt(requestId),
                    status: status
                };
                
                if (status === '已拒绝') {
                    updateDTO.rejectReason = $('#rejectReason').val();
                } else if (status === '已完成') {
                    updateDTO.bookId = parseInt($('#bookId').val());
                    
                    if (!updateDTO.bookId) {
                        alert('请输入关联书籍ID');
                        return;
                    }
                }
                
                fetch('/api/book-requests/status', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(updateDTO)
                })
                .then(response => response.json())
                .then(data => {
                    if (data.status === 200) {
                        $('#processModal').modal('hide');
                        alert('处理成功');
                        loadAllRequests(allCurrentPage);
                    } else {
                        alert(data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('处理失败，请稍后重试');
                });
            });
            
            // 删除请求
            function deleteRequest(requestId) {
                if (!confirm('确定要删除这个请求吗？')) {
                    return;
                }
                
                fetch(`/api/book-requests/${requestId}`, {
                    method: 'DELETE'
                })
                .then(response => response.json())
                .then(data => {
                    if (data.status === 200) {
                        alert('删除成功');
                        loadMyRequests(myCurrentPage);
                    } else {
                        alert(data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('删除失败，请稍后重试');
                });
            }
            
            // 根据状态获取徽章样式
            function getStatusBadgeClass(status) {
                switch (status) {
                    case '待处理':
                        return 'badge-secondary';
                    case '已接受':
                        return 'badge-primary';
                    case '已拒绝':
                        return 'badge-danger';
                    case '已完成':
                        return 'badge-success';
                    default:
                        return 'badge-secondary';
                }
            }
        });
    </script>
</body>
</html> 